from waflib import Logs


def em_resource(task):
    packager = task.env.EMSCRIPTEN_ROOT + '/tools/file_packager.py'
    task.exec_command(['python',
                       packager,
                       task.outputs[0].abspath(),
                       '--embed',
                       task.inputs[0].abspath(),
                       '--js-output=' + task.outputs[0].abspath()])


def configure(conf):
    conf.find_program('node', var='NODE', errmsg='node is not installed')

    # Make sure we're about to modify the 'local' conf:
    prev_env = conf.env
    conf.set_env(conf.all_envs['local'])

    conf.load('emscripten')

    # The standard lib emscripten bundles uses a different format
    # for its stack guard!!
    conf.env.CFLAGS.append('-D_TIME_H')

    # For unit tests: DUMA depends on pthread,
    # which I didn't get to work with emscripten.
    conf.env.DEFINES.append('DUMA_DISABLED')

    # Flags that emcc doesn't support, just remove them:
    unwanted_cflags = ['-gdwarf-4']

    if 'RELEASE' not in conf.env.DEFINES:
        conf.env.EMCC_DEBUG = 2
        conf.env['CFLAGS'].extend(['-g4'])
        unwanted_cflags.extend(['-g3', '-g'])

    conf.env['CFLAGS'] = filter(
        lambda flag: flag not in unwanted_cflags,
        conf.env['CFLAGS']
    )

    conf.env.EMX_OTHER_SETTINGS = [
        'SAFE_HEAP=1',
        # absurdly large value so we don't worry:
        'RESERVED_FUNCTION_POINTERS=1000',
        'ERROR_ON_UNDEFINED_SYMBOLS=1'
    ]

    conf.add_platform_defines(conf.env)

    conf.recurse('integration_tests')

    conf.setenv('emscripten', conf.env)

    conf.set_env(prev_env)


def apply_config_for_applib_and_test_rocky_emx_builds(bld):
    bld.env.DEFINES.append("APPLIB_EMSCRIPTEN=1")

    # __builtin_return_address() doesn't seem to be supported by Emscripten,
    # it fail at runtime due to a missing `llvm_return_address` function.
    bld.env.CFLAGS.extend(['-D__builtin_return_address(level)=(0)'])

    jerry_api_js = bld.path.make_node('jerry_api.js')
    timeshift_js = bld.path.find_node('timeshift-js/timeshift.js')
    html_binding_js = bld.path.make_node('html-binding.js')
    bld.env.EMX_PRE_JS_FILES = [jerry_api_js, timeshift_js]
    bld.env.EMX_POST_JS_FILES = [html_binding_js]
    # use external transformation script instead of --pre-js and --post-js so
    # we can replace functions and wrap entire file without interfering with
    # --embed-file
    transform_js_node_and_args = [bld.path.make_node('transform_js.py')]
    if bld.variant == 'test_rocky_emx':
        transform_js_node_and_args.append(' --unittest')
    bld.env.EMX_TRANSFORM_JS_NODE_AND_ARGS = transform_js_node_and_args


def build(bld):
    if bld.variant == 'test':
        bld.recurse('tests')
        return

    # Extend waf's 'cprogram' feature with Emscripten-specific things:
    bld.load('emscripten')

    apply_config_for_applib_and_test_rocky_emx_builds(bld)

    # Fine to use 'stlib' here vs emscripten_program, because we're only
    # invoking emcc to generate an archive file, so only 'standard' compiler
    # flags need to be passed.
    bld.objects(source=['emscripten_jerry_api.c'],
                target='emscripten_jerry_api',
                use=['jerry_port_includes'])

    if bld.variant == 'test_rocky_emx':
        return

    # Copy stuff from html folder:
    html_node = bld.path.find_dir('html')
    html_bld_node = bld.path.get_bld().make_node('html')
    for file in html_node.ant_glob('**/*'):
        bld(rule="cp ${SRC} ${TGT}",
            source=file,
            target=html_bld_node.make_node(file.path_from(html_node)))

    pbpack = bld.path.parent.parent.get_bld().make_node('system_resources.pbpack')
    exported_functions = bld.path.make_node('exported_functions.json')
    sources = bld.path.ant_glob('*.c', excl='emscripten_jerry_api.c')
    rockyjs_node = html_bld_node.make_node('rocky.js')
    bld.program(source=sources,
                target=rockyjs_node,
                emx_pre_js_files=[],
                emx_post_js_files=[],
                emx_exported_functions=exported_functions,
                emx_other_settings=[],
                emx_embed_files=[pbpack],
                use=['emscripten_jerry_api',
                     'applib',
                     'applib_includes',
                     'nanopb',
                     'fw_includes',
                     'libutil',
                     'upng'])

    bld.recurse('integration_tests')

    def print_index_html_path(bld):
        index_html_path = html_bld_node.find_node('index.html').abspath()
        Logs.pprint('PINK',
                    'Built Rocky Simulator: file://{}'.format(index_html_path))
    bld.add_post_fun(print_index_html_path)


# vim:filetype=python
